import { getInfo } from '@/api/sys/user'
import { login, logout } from '@/api/sys/login'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    userName: '',
    userId: '',
    mobile: '',
    email: '',
    createDate: '',
    avatorImgPath: '',
    token: getToken(),
    hasGetInfo: false
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setToken (state, token) {
      if (typeof token === 'object') {
        state.token = token.token
        setToken(token.token, token.expire)
      } else {
        state.token = token
        setToken(token, 0)
      }
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    }
  },
  getters: {
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { userName, password, uuid, captcha, address }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password,
          uuid,
          captcha,
          address
        }).then(res => {
          if (res.code === 200) {
            commit('setToken', res)
          }
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setHasGetInfo', false)
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getInfo(state.token).then(res => {
            if (res.code !== 401) {
              if (res.user.avatar !== undefined) {
                commit('setAvator', 'data:image/jpeg;base64,' + res.user.avatar)
              } else {
                commit('setAvator', 'https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png')
              }
              commit('setUserName', res.user.name)
              commit('setUserId', res.user.userId)
              state.mobile = res.user.mobile
              state.email = res.user.email
              state.createDate = res.user.createTime
              commit('setHasGetInfo', true)
              resolve(res.user)
            }
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
